//
// Created by 24137 on 2021/7/3.
//

#ifndef DATA_STRUCTURE_STRING_H
#define DATA_STRUCTURE_STRING_H

#endif //DATA_STRUCTURE_STRING_H

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef struct
{
    char *ch;
    int length;
} String;

bool clean(String *string)
{
    string->ch = NULL;
    string->length = 0;
}

bool StrAssign(String *string, char *chars)
{
    clean(string);
    int i = 0;
    char *c = chars;
    for (; *c; i++, c++);
    if (!i)return true;
    else
    {
        string->ch = (char *) malloc(i * sizeof(char));
        string->length = i;
        char *ch = chars;
        char *ch1 = string->ch;
        while (*ch)
        {
            *ch1++ = *ch++;
        }
        return true;
    }
}

int length(String *string)
{
    return string->length;
}

int compare(String s1, String s2)
{
    for (int i = 0; i < length(&s1) && i < length(&s2); i++)
    {
        if (s1.ch[i] != s2.ch[i])
            return s1.ch[i] - s2.ch[i];
    }
    return length(&s1) - length(&s2);
}

bool concat(String *newString, String s1, String s2)
{
    clean(newString);
    newString->ch = (char *) malloc(sizeof(char) * (length(&s1) + length(&s2)));
    newString->length = length(&s1) + length(&s2);

    char *string = newString->ch;
    char *ch = s1.ch;
    char *ch1 = s2.ch;
    while (*ch != '\0')//不能使用while(*c) 自定义的字符串
    {
        *string++ = *ch++;
    }
    while (*ch1!='\0')
    {
        *string++ = *ch1++;

    }
    return true;
}

bool subString(String *sub, String string, int pos, int length)
{
    if (pos < 1 || pos > string.length || length > string.length - pos + 1 || length < 0)
    {
        return false;
    }
    clean(sub);
    if (!length)return true;
    else
    {
        sub->ch = (char *) malloc(sizeof(char) * length);
        sub->length = length;

        char *string1 = sub->ch;
        char *ch = string.ch + pos - 1;
        while (ch < string.ch + pos + length - 1)
        {
            *string1++ = *ch++;
        }
        return true;
    }
}

void visit(String string)
{
    if (!string.ch)
    {
        return;
    }
    char *ch = string.ch;
    while (*ch)
    {
        printf("%c", *ch++);
    }
    printf("\n");
}

